#include "N1Array.h"
#include "N1Lib.h"

N1Array::N1Array() : m_nCount(0), m_ptr(NULL), m_nAllocatedCount(0)
{
}

N1Array::N1Array(uint32 size) : m_nCount(0),  m_nAllocatedCount(size)
{
    m_ptr = (N1Object**)N1Malloc(size * sizeof(N1Object*));
    memset(m_ptr, 0, size * sizeof(N1Object*));
}

N1Array::N1Array(const N1Array &array) : m_nCount(array.m_nCount)
{
    m_ptr = (N1Object**)N1Malloc(m_nCount * sizeof(N1Object*));
    memcpy(m_ptr, array.m_ptr, m_nCount * sizeof(N1Object*));
    m_nAllocatedCount = m_nCount;
}

N1Array::~N1Array()
{
    for(uint32 i=0;i<m_nCount;i++)
    {
        m_ptr[i]->release();
    }
    N1Free(m_ptr);
}

N1NAME_DEF(N1Array)

//void N1Array::setCount(uint32 count);

void N1Array::append(uint32 newCount)
{
    N1Assert(newCount>m_nCount);

    N1Object** ptr = (N1Object**)N1Malloc(newCount * sizeof(N1Object*));
    memcpy(ptr, m_ptr, m_nCount * sizeof(N1Object*));
    memset(ptr + m_nCount, 0, (newCount - m_nCount)*sizeof(N1Object*));
    N1Free(m_ptr);
    m_ptr = ptr;
    m_nAllocatedCount = newCount;
}

uint32 N1Array::add(N1Object* obj)
{
    if(m_nAllocatedCount==m_nCount)
    {
        uint32 newSize = N1GetNewSizeByLog2(m_nAllocatedCount, 1, 1);
        append(newSize);
    }
    m_ptr[m_nCount] = obj->retain();
    return ++m_nCount;
}

#ifdef N1LIB_SELFTEST



#endif
